package com.huatai.bpmn.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.bpmn.entity.*;
import com.huatai.bpmn.entity.dto.BusinessDto;
import com.huatai.bpmn.entity.dto.CandidateTaskDto;
import com.huatai.bpmn.entity.dto.PageDto;
import com.huatai.bpmn.entity.vo.CompleteTaskVO;
import com.huatai.bpmn.entity.vo.DeploymentVO;
import com.huatai.bpmn.entity.vo.HistoryVO;
import com.huatai.bpmn.entity.vo.TaskVO;
import com.huatai.bpmn.service.*;
import com.huatai.bpmn.mapper.TbBusinessMapper;
import com.huatai.bpmn.utils.Activiti7Util;
import com.huatai.common.api.R;
import com.huatai.common.util.AuthUtil;
import com.huatai.common.util.ObjectUtil;
import com.huatai.common.util.StringUtil;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 聂贞吉
 * @description 针对表【tb_business】的数据库操作Service实现
 * @createDate 2023-07-07 15:34:25
 */
@Service
public class TbBusinessServiceImpl extends ServiceImpl<TbBusinessMapper, TbBusinessEntity> implements TbBusinessService {

	@Value("${history.consent}")
	private String consent;
	@Value("${history.notConsent}")
	private String notConsent;
	@Value("${history.consentColor}")
	private String consentColor;
	@Value("${history.notConsentColor}")
	private String notConsentColor;
	@Value("${history.reload}")
	private String reload;

	@Autowired
	private TbUserDeploymentService tbUserDeploymentService;

	@Autowired
	TbBusinessService businessService;
	@Autowired
	private TbCompleteTaskStatusService completeTaskStatusService;
	@Autowired
	private DeployFormMappingService deployFormMappingService;

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	private BasicLoadService basicLoadService;

	@Autowired
	private BasicDataService basicDataService;

	@Autowired
	private TbCommitService commitService;

	@Autowired
	private TbBusinessMapper businessMapper;

	@Autowired
	private FileService fileService;

	@Autowired
	private ExternalParameterService externalParameterService;


	/**
	 * 查询当前用户候选人有哪些待处理任务
	 *
	 * @param candidateTaskDto
	 * @return
	 */
	@Override
	public R<Map<String, Object>> findToDoTask(CandidateTaskDto candidateTaskDto) {
		//候选人名称
		String userId = AuthUtil.getUser().getUserId().toString();
		candidateTaskDto.setUserId(userId);
		UserDetails userDetails = userRoleService.loadUserByUsername(userId);
		//获取到当期用户的角色id
		Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
		List<String> roleIds = new ArrayList<>(authorities.size());
		candidateTaskDto.setPage(((candidateTaskDto.getPage() - 1) * candidateTaskDto.getLimit()));
		String groupRoleIdS = "";
		for (GrantedAuthority authority : authorities) {
			roleIds.add(authority.getAuthority());
			groupRoleIdS += authority.getAuthority() + ",";
		}
		candidateTaskDto.setRoleIds(groupRoleIdS.substring(0, groupRoleIdS.length() - 1));
		List<TaskVO> toDoTaskList = businessMapper.findToDoTask(candidateTaskDto);
		TaskService taskService = Activiti7Util.taskService;
		long total = taskService.createTaskQuery()
			.taskCandidateUser(userId)//设置候选用户
			.taskCandidateGroupIn(roleIds)//设置候选组
			.count();
		Map<String, Object> map = new HashMap<>();
		map.put("taskPendingList", toDoTaskList);
		map.put("total", Integer.parseInt(String.valueOf(total)));
		return R.data(map);
	}

	/**
	 * 查询代办任务状态
	 *
	 * @param processInstanceId
	 * @return·
	 */
	private String findToDoTaskStatus(String processInstanceId) {
		TaskService taskService = Activiti7Util.taskService;
		Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
		if (task == null) {
			TbBusinessEntity tbBusiness = businessService.getOne(new LambdaQueryWrapper<TbBusinessEntity>()
				.eq(TbBusinessEntity::getProcinstId, processInstanceId));
			tbBusiness.setStatus(1);
			businessService.updateById(tbBusiness);
			return "已完成";
		}
		return "等待处理";
	}

	/**
	 * 获取任务申请人
	 *
	 * @param processInstanceId
	 * @return
	 */
	private UserEntity findUserNameById(String processInstanceId) {
		TbBusinessEntity business = businessService.getOne(new LambdaQueryWrapper<TbBusinessEntity>()
			.eq(TbBusinessEntity::getProcinstId, processInstanceId));
		String userId = business.getCreateUserid();
		LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(UserEntity::getUserId, userId);
		UserEntity user = userService.getOne(wrapper);
		return user;
	}

	/**
	 * 拾取任务，完成任务
	 *
	 * @param jsonObject
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R<Boolean> fulfilTask(JSONObject jsonObject) {
		String procinstId = jsonObject.getString("procinstId");
		String userId = AuthUtil.getUser().getUserId().toString();
		String fqrId = jsonObject.getString("fqrId");
		String status = jsonObject.getString("status");
		String suggest = jsonObject.getString("suggest");
		JSONObject param = jsonObject.getJSONObject("param");
		JSONObject data = param.getJSONObject("data");
		JSONObject bpmParam = param.getJSONObject("param");
		bpmParam.put("fqrId", fqrId);
		bpmParam.put("status", status);
		bpmParam.put("userId", userId);
		//审批建议
		TaskService taskService = Activiti7Util.taskService;
		UserDetails userDetails = userRoleService.loadUserByUsername(userId);
		Task task = taskService.createTaskQuery().processInstanceId(procinstId).singleResult();
		if ("暂存".equals(status)) {
			//暂存修改业务流水数据
			updateBusinessData(param, procinstId, data, bpmParam, userId);
			return R.data(true);
		}
		boolean isTrue = Activiti7Util.claimTaskAndCompleteTask(task.getId(), userDetails, bpmParam);
		//查询runTask中任务实例是否还存在如果不存在更改业务表中任务完成的状态
		ProcessInstance processInstance = Activiti7Util.runtimeService.createProcessInstanceQuery().processInstanceId(procinstId).singleResult();
		if (isTrue) {
			//修改业务流水数据
			updateBusinessData(param, procinstId, data, bpmParam, userId);
			//添加审批建议
			TbCompleteTaskStatusEntity completeTaskStatus = new TbCompleteTaskStatusEntity();
			completeTaskStatus.setTaskId(task.getId());
			completeTaskStatus.setStatus(status);
			completeTaskStatus.setApprovalProposal(suggest);
			//添加到审批意见表中
			completeTaskStatusService.save(completeTaskStatus);

		}
		if (ObjectUtil.isEmpty(processInstance)) {
			TbBusinessEntity businessEntity = businessService.getOne(new LambdaQueryWrapper<TbBusinessEntity>()
				.eq(TbBusinessEntity::getProcinstId, procinstId));
			//修改任务是否完成状态
			businessEntity.setStatus(1);
			//审核完成之后数据存储
			businessService.updateById(businessEntity);
			//审核完成之后数据存储
//			basicDataService.addList(procinstId);
			//调用执行最后一级审批逻辑代码
			commitService.commit(businessEntity.getDeployKey(), jsonObject);
		}
		return R.data(isTrue);
	}

	/**
	 * 修改业务流水数据
	 *
	 * @param param      外部参数
	 * @param procinstId 业务流水号
	 * @param data       表格数据
	 * @param bpmParam   流程参数
	 * @param userId     用户id
	 */
	private void updateBusinessData(JSONObject param, String procinstId, JSONObject data, JSONObject bpmParam, String userId) {
		//保存审批附件
		JSONArray files = param.getJSONArray("files") == null ? new JSONArray() : param.getJSONArray("files");
		for (int i = 0; i < files.size(); i++) {
			JSONObject file = files.getJSONObject(i);
			String fileType = file.getString("fileType");
			String path = file.getString("path");
			LambdaQueryWrapper<FileEntity> fileQuery = Wrappers.lambdaQuery();
			fileQuery
				.eq(FileEntity::getFilePath, path)
				.eq(FileEntity::getFileType, fileType);
			FileEntity fileEntity = new FileEntity();
			fileEntity.setDeleted(false);
			fileEntity.setBusinessKey(procinstId);
			fileService.update(fileEntity, fileQuery);
		}
		//根据审批数据修改流水数据
		TbBusinessEntity business = businessService.getOne(new LambdaQueryWrapper<TbBusinessEntity>()
			.eq(TbBusinessEntity::getProcinstId, procinstId));
		JSONObject extend = business.getExtend();
		JSONObject extendInnerData = extend.getJSONObject("data");
		JSONObject extendInnerParam = extend.getJSONObject("param");
		Set<String> dataKeys = data.keySet();
		for (String dataKey : dataKeys) {
			extendInnerData.put(dataKey, data.getJSONArray(dataKey));
		}
		extendInnerParam.putAll(bpmParam);
		extend.put("data", extendInnerData);
		extend.put("param", extendInnerParam);
		business.setExtend(extend);
		business.setUpdateUserid(Long.parseLong(userId));
		businessService.updateById(business);
	}

	/**
	 * 业务表和表单中数据进行修改
	 *
	 * @param procinstId
	 * @param param
	 */
	private void updateBusinessAndBasicLoad(String procinstId, JSONObject param) {
		//查询出当前实例的流程数据
		TbBusinessEntity business = businessService.getOne(new LambdaQueryWrapper<TbBusinessEntity>()
			.eq(TbBusinessEntity::getProcinstId, procinstId));
		//修改参数
		business.setExtend(param);
		businessService.updateById(business);
		List<JSONObject> data = param.getJSONArray("data").toJavaList(JSONObject.class);
		for (JSONObject theJson : data) {
			theJson.put("place", business.getExternalParameterId());
		}
		//修改表单数据
		basicLoadService.updateList(data, JSONObject.toJSONString(business));
	}


	/**
	 * 查看流程实例的历史处理信息
	 *
	 * @param candidateTaskDto
	 * @return
	 */
	@Override
	public R<Map<String, Object>> taskHistoryInfo(CandidateTaskDto candidateTaskDto) {
		List<HistoryVO> list = businessMapper.taskHistoryInfo(candidateTaskDto);
		List<HistoryVO> historyVOS = new ArrayList<>();
		String formKey = "";
		for (HistoryVO hai : list) {
			if (hai.getActType().equals("startEvent") || hai.getActType().equals("userTask") || hai.getActType().equals("endEvent")) {
				HistoryVO historyVO = new HistoryVO();
				historyVO.setStartTime(hai.getStartTime());
				historyVO.setActivityName(hai.getActivityName());
				historyVO.setNodeForm(hai.getNodeForm());
				//如果是开始节点
				if ("startEvent".equals(hai.getActType())) {
					continue;
					/*DeployFormMappingEntity deployFormMapping = deployFormMappingService.getOne(new LambdaQueryWrapper<DeployFormMappingEntity>()
						.eq(DeployFormMappingEntity::getDeploymentid, hai.getDeployId()));
					historyVO.setNodeForm(deployFormMapping.getExternalParameterId());*/
				}
				//如果是结束节点
				if ("endEvent".equals(hai.getActType())) {
					historyVO.setNodeForm(formKey);
				}
				formKey = hai.getNodeForm();
				if (ObjectUtil.isNotEmpty(hai.getEndTime())) {
					historyVO.setEndTime(hai.getEndTime());
				}
				setAssigneeAndSetColourMethod(hai, historyVO);
				historyVOS.add(historyVO);
			}
		}
		Map<String, Object> map = new HashMap<>();
		map.put("historyTaskList", historyVOS);
		return R.data(map);
	}

	/**
	 * 查询候选人已办任务
	 *
	 * @param candidateTaskDto
	 * @return
	 */
	@Override
	public R<Map<String, Object>> findCompleteTask(CandidateTaskDto candidateTaskDto) {
		Long userId = AuthUtil.getUser().getUserId();
		Integer page = candidateTaskDto.getPage();
		Integer limit = candidateTaskDto.getLimit();
		candidateTaskDto.setPage((page - 1) * limit);
		candidateTaskDto.setUserId(userId.toString());
		List<CompleteTaskVO> completeTask = businessMapper.findCompleteTask(candidateTaskDto);
		long total = Activiti7Util.historyService.createHistoricTaskInstanceQuery()
			.taskAssignee(userId.toString())
			.count();
		Map<String, Object> map = new HashMap<>();
		map.put("taskCandidateList", completeTask);
		map.put("total", Integer.parseInt(String.valueOf(total)));
		return R.data(map);
	}

	/**
	 * 查询某个代办任务详情
	 *
	 * @param jsonObject
	 * @return
	 */
	@Override
	public Object findToDoTaskParticulars(JSONObject jsonObject) {
		String procinstId = jsonObject.getString("procinstId");
		TbBusinessEntity business = findBusiness(procinstId);
		JSONObject extend = business.getExtend();
		JSONArray data = extend.getJSONObject("param").getJSONArray("data");
		return data;
	}

	/**
	 * 流程部署
	 *
	 * @param file
	 * @param deployName
	 * @param externalParameterId
	 * @return
	 * @throws IOException
	 */
	@Override
	public R<Map<String, Object>> deploy(MultipartFile file, String deployName, String externalParameterId) throws IOException {
		//判断是已经存在place关联字段是否唯一
	/*	DeployFormMappingEntity deployFormMapping = deployFormMappingService.getOne(new LambdaQueryWrapper<DeployFormMappingEntity>()
			.eq(DeployFormMappingEntity::getExternalParameterId, externalParameterId));
		if (ObjectUtil.isNotEmpty(deployFormMapping)){
			throw new RuntimeException("该表单已经被绑定请跟换");
		}*/
		//读书文件流
		InputStream inputStream = file.getInputStream();

		//创建processEngine
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		//得到repositoryService实例
		RepositoryService repositoryService = processEngine.getRepositoryService();
		//使用repositoryService进行部署
		Deployment deployment = repositoryService.createDeployment()
			.addInputStream(file.getOriginalFilename(), inputStream)
			.name(deployName)
			.deploy();
		//将部署的id和表单进行绑定
		DeployFormMappingEntity deployFormMappingEntity = new DeployFormMappingEntity();
		deployFormMappingEntity.setDeploymentid(deployment.getId());
		deployFormMappingEntity.setExternalParameterId(externalParameterId);
		deployFormMappingService.save(deployFormMappingEntity);
		//部署信息
		Map<String, Object> map = new HashMap<>();
		map.put("deploymentId", deployment.getId());
		map.put("deploymentName", deployment.getName());
		return R.data(map);
	}

	/**
	 * 获取部署的流程集合
	 *
	 * @param
	 * @return
	 */
	@Override
	public R<Map<String, Object>> getDeployList(PageDto pageDto) {
		RepositoryService repositoryService = Activiti7Util.repositoryService;
		ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
		List<ProcessDefinition> list = new ArrayList<>();
		if (pageDto.getPage() == 0 || pageDto.getLimit() == 0) {
			list = processDefinitionQuery.latestVersion().list();
		} else {
			list = processDefinitionQuery.latestVersion()
				.listPage((pageDto.getPage() - 1) * pageDto.getLimit(), pageDto.getLimit());
		}
		long total = processDefinitionQuery.latestVersion().count();
		List<DeploymentVO> deploymentVOList = new ArrayList<>();

		List<DeployFormMappingEntity> formMapping = deployFormMappingService.list();
		List<ExternalParameterEntity> configFormList = externalParameterService.list();
		for (ProcessDefinition processDefinition : list) {
			Deployment deployment = findDeploymentInfo(processDefinition.getDeploymentId());
			DeploymentVO deploymentVO = new DeploymentVO();
			deploymentVO.setDeployId(deployment.getId());
			deploymentVO.setDeployName(deployment.getName());
			deploymentVO.setCreateTime(deployment.getDeploymentTime());
			deploymentVO.setDefinitionKey(findProcdefKey(deployment.getId()));
			for (DeployFormMappingEntity deployFormMappingEntity : formMapping) {
				if (deployFormMappingEntity.getDeploymentid().equals(deployment.getId())) {
					deploymentVO.setPlace(deployFormMappingEntity.getExternalParameterId());
					deploymentVO.setCompleteFormKey(deployFormMappingEntity.getCompleteId());
					break;
				}
			}
//			deploymentVO.setPlace(findExternalParameterId(deployment.getId()));
			deploymentVOList.add(deploymentVO);
		}
		for (DeploymentVO deploymentVO : deploymentVOList) {
			for (ExternalParameterEntity externalParameterEntity : configFormList) {
				if (deploymentVO.getPlace().equals(externalParameterEntity.getId())) {
					deploymentVO.setFormName(externalParameterEntity.getName());
				}
			}
		}
		Map<String, Object> map = new HashMap<>();
		deploymentVOList.sort((t1, t2) -> t2.getCreateTime().compareTo(t1.getCreateTime()));
		map.put("deploymentList", deploymentVOList);
		map.put("total", Integer.parseInt(String.valueOf(total)));
		return R.data(map);
	}

	/**
	 * 获取流程部署绑定关系的表单
	 *
	 * @param id
	 * @return
	 */
	private String findExternalParameterId(String id) {
		DeployFormMappingEntity formMapping = deployFormMappingService.getOne(new LambdaQueryWrapper<DeployFormMappingEntity>()
			.eq(DeployFormMappingEntity::getDeploymentid, id));
		return formMapping.getExternalParameterId();
	}

	/**
	 * 根据id删除流程实例
	 *
	 * @param processInstanceId 实例id
	 * @param reason            原因
	 * @return
	 */
	@Override
	public R<String> removeFlowInstance(String processInstanceId, String reason) {
		RuntimeService runtimeService = Activiti7Util.runtimeService;
		businessService.remove(new LambdaQueryWrapper<TbBusinessEntity>()
			.eq(TbBusinessEntity::getProcinstId, processInstanceId));
		runtimeService.deleteProcessInstance(processInstanceId, reason);
		return R.data("删除成功");
	}

	/**
	 * 根据部署的id查询对应的表单
	 *
	 * @param deploymentId
	 * @return
	 */
	@Override
	public R<JSONObject> findDeployFormById(String deploymentId) {
		DeployFormMappingEntity deployFormMappingServiceOne = deployFormMappingService.getOne(new LambdaQueryWrapper<DeployFormMappingEntity>()
			.eq(DeployFormMappingEntity::getDeploymentid, deploymentId));
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("place", deployFormMappingServiceOne.getExternalParameterId());
		return R.data(jsonObject);
	}

	/**
	 * 查询当前用户已发起的申请
	 *
	 * @param candidateTaskDto
	 * @return
	 */
	@Override
	public R<Map<String, Object>> findOneselfApplication(CandidateTaskDto candidateTaskDto) {
		candidateTaskDto.setPage((candidateTaskDto.getPage() - 1) * candidateTaskDto.getLimit());
		List<TaskVO> taskList = businessMapper.findOneselfApplication(candidateTaskDto);
		Long userId = AuthUtil.getUser().getUserId();
		LambdaQueryWrapper<TbBusinessEntity> wrapper = new LambdaQueryWrapper<TbBusinessEntity>()
			.eq(TbBusinessEntity::getCreateUserid, userId);
		wrapper.orderByDesc(TbBusinessEntity::getCreateTime);
		long count = this.count(wrapper);
		Map<String, Object> map = new HashMap<>();
		map.put("taskSentList", taskList);
		map.put("total", Integer.parseInt(String.valueOf(count)));
		return R.data(map);
	}

	/**
	 * 查询所有已完成的任务
	 *
	 * @param candidateTaskDto
	 * @return
	 */
	@Override
	public R<Map<String, Object>> selectCompleteTaskAll(CandidateTaskDto candidateTaskDto) {
		LambdaQueryWrapper<TbBusinessEntity> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(TbBusinessEntity::getStatus, 1);
		wrapper.eq(TbBusinessEntity::getDeployKey, candidateTaskDto.getDeployKey());
		long count = businessService.count(wrapper);
		candidateTaskDto.setPage((candidateTaskDto.getPage() - 1) * candidateTaskDto.getLimit());
		List<TaskVO> taskVOList = businessMapper.selectCompleteTaskAll(candidateTaskDto);
		Map<String, Object> map = new HashMap<>();
		map.put("taskCompleteList", taskVOList);
		map.put("total", Integer.parseInt(String.valueOf(count)));
		return R.data(map);
	}

	@Override
	public void getDeploymentFlowChart(String definitionKey, HttpServletResponse response) throws IOException {
		RepositoryService repositoryService = Activiti7Util.repositoryService;
		//查询出部署的流程
		ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().latestVersion().processDefinitionKey(definitionKey).singleResult();
		InputStream bpmnIns = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getResourceName());
		byte[] buff = new byte[1024];
		int n;
		ServletOutputStream outputStream = response.getOutputStream();
		while ((n = bpmnIns.read(buff)) != -1) {
			outputStream.write(buff, 0, n);
		}
		outputStream.flush();
		outputStream.close();
		bpmnIns.close();
	}

	/**
	 * 根据流程实例id查询对应的流程部署id
	 *
	 * @param processInstanceId 实例id
	 * @return
	 */
	@Override
	public R getDeploymentId(String processInstanceId) {
		TbBusinessEntity tbBusiness = businessService.getOne(new LambdaQueryWrapper<TbBusinessEntity>().eq(TbBusinessEntity::getProcinstId, processInstanceId));
		return R.data(tbBusiness.getDeployId());
	}

	/**
	 * 获取节点表单数据
	 *
	 * @param processInstanceId
	 * @return
	 */
	@Override
	public JSONObject getNodeData(String processInstanceId) {
		LambdaQueryWrapper<TbBusinessEntity> businessQuery = Wrappers.lambdaQuery();
		businessQuery
			.eq(TbBusinessEntity::getDeleted, false)
			.eq(TbBusinessEntity::getProcinstId, processInstanceId);
		TbBusinessEntity businessEntity = businessService.getOne(businessQuery);
		JSONObject extend = businessEntity.getExtend();
		LambdaQueryWrapper<FileEntity> fileQuery = Wrappers.lambdaQuery();
		fileQuery
			.eq(FileEntity::getBusinessKey, processInstanceId)
			.eq(FileEntity::getDeleted, false);
		List<FileEntity> fileList = fileService.list(fileQuery);
		extend.put("fqrId", businessEntity.getCreateUserid());
		extend.put("files", fileList);
		extend.put("processInstanceId", businessEntity.getProcinstId());
		return extend;
	}


	/**
	 * 获取当前用户已关注的流程发起信息
	 */
	@Override
	public R<Map<String, Object>> findOneselfApplicationAndDeployment(CandidateTaskDto candidateTaskDto) {
		LambdaQueryWrapper<TbBusinessEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(TbBusinessEntity::getDeployKey, candidateTaskDto.getDeployKey());
		long count = this.count(wrapper);
		HashMap<String, Object> map = new HashMap<>();
		map.put("total", count);
		map.put("taskVoList", new ArrayList<>());
		if (count==0){
			return R.data(map);
		}
		candidateTaskDto.setPage((candidateTaskDto.getPage() - 1) * candidateTaskDto.getLimit());
		LambdaQueryWrapper<TbUserDeploymentEntity> userDeployWrapper = Wrappers.lambdaQuery();
		userDeployWrapper.eq(TbUserDeploymentEntity::getUserId,candidateTaskDto.getUserId())
				.eq(TbUserDeploymentEntity::getDeployKey, candidateTaskDto.getDeployKey());
		//获取到该用户对该事项的关注sql
		TbUserDeploymentEntity one = tbUserDeploymentService.getOne(userDeployWrapper);
		candidateTaskDto.setAttentionSql(one.getAttentionSql());
		List<TaskVO> taskVoList = businessMapper.findOneselfApplicationAndDeployment(candidateTaskDto);
		map.put("total", count);
		map.put("taskVoList", taskVoList);
		return R.data(map);
	}

	@Override
	public List<TbBusinessEntity> getBusinessList(BusinessDto businessDto) {
		List<TbBusinessEntity> list = this.list();

		List<TbBusinessEntity> newList = list.stream().collect(Collectors.toList());

		List<String> formList = businessDto.getForm();
		List<String> paramList = businessDto.getParam();


		list.forEach(x -> {
			JSONObject data = x.getExtend();
			//获取表格数据
			HashMap<String, Object> formData = (HashMap<String, Object>) data.get("data");
			//获取表单数据
			HashMap<String, String> paramData = (HashMap<String, String>) data.get("param");

			//当formFlag存在多个数据时，如果其中一个为空，其他数据不为空则不删除数据
			boolean formFlag = false;
			if (formList.size() > 0) {
				//表格数据
				for (String s : formList) {
					Object o = formData.get(s);
					if (!ObjectUtil.isEmpty(o)) {
						formFlag = true;
					}
					if (formFlag) {
						break;
					}
				}

			}

			//当formFlag存在多个数据时，如果其中一个为空，其他数据不为空则不删除数据
			boolean paramFlag = false;
			if (paramList.size() > 0) {
				//表格数据
				for (String s : paramList) {
					Object o = paramData.get(s);
					if (!ObjectUtil.isEmpty(o)) {
						paramFlag = true;
					}
					if (paramFlag) {
						break;
					}
				}

			}

			if (formList.size()>0||paramList.size() > 0){
				if (!formFlag&&!paramFlag) {
					newList.remove(x);
				}
			}

		});
		return newList;
	}


	/**
	 * 根据流程实例查找任务
	 *
	 * @param procinstId
	 */
	private HistoricTaskInstance findRuTask(String procinstId) {
		List<HistoricTaskInstance> list = Activiti7Util.historyService.createHistoricTaskInstanceQuery()
			.processInstanceId(procinstId).orderByHistoricTaskInstanceEndTime().desc().list();
		HistoricTaskInstance historicTaskInstance = list.get(0);
		return historicTaskInstance;
	}


	/**
	 * 获取流程部署流程的信息
	 *
	 * @param deploymentId
	 * @return
	 */
	private Deployment findDeploymentInfo(String deploymentId) {
		RepositoryService repositoryService = Activiti7Util.repositoryService;
		Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
		return deployment;
	}

	/**
	 * 获取部署流程的key值
	 *
	 * @param deploymentId
	 * @return
	 */
	private String findProcdefKey(String deploymentId) {
		RepositoryService repositoryService = Activiti7Util.repositoryService;
		ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
		System.out.println(processDefinition);
		return processDefinition.getKey();
	}

	/**
	 * 查询业务流水表中数据
	 *
	 * @param processInstanceId
	 * @return
	 */
	private TbBusinessEntity findBusiness(String processInstanceId) {
		TbBusinessEntity business = businessService.getOne(new LambdaQueryWrapper<TbBusinessEntity>()
			.eq(TbBusinessEntity::getProcinstId, processInstanceId));
		return business;
	}

	/**
	 * 查询任务完成状态表信息
	 *
	 * @param id
	 */
	private TbCompleteTaskStatusEntity findCompleteTaskStatus(String id) {
		TbCompleteTaskStatusEntity statusServiceOne = completeTaskStatusService.getOne(new LambdaQueryWrapper<TbCompleteTaskStatusEntity>()
			.eq(TbCompleteTaskStatusEntity::getTaskId, id));
		return statusServiceOne;
	}

	/**
	 * 设置受理人和历史信息颜色
	 *
	 * @param hai
	 * @param historyVO
	 * @return
	 */
	private void setAssigneeAndSetColourMethod(HistoryVO hai, HistoryVO historyVO) {
		if (hai.getActType().equals("userTask") && StringUtil.isBlank(hai.getAssignee())) {
			historyVO.setAssignee(findCandidate(hai.getProcessInstanceId()));
		} else if (hai.getActType().equals("userTask") && StringUtil.isNotBlank(hai.getAssignee())) {
			historyVO.setAssignee(findUserRealName(hai.getAssignee()));
		} else if (hai.getActType().equals("startEvent") && StringUtil.isBlank(hai.getAssignee())) {
			String userName = findStartEventAssignee(hai.getProcessInstanceId());
			historyVO.setAssignee(userName);
			//蓝色
			historyVO.setColour(consentColor);
		} else if (hai.getActType().equals("startEvent") && StringUtil.isNotBlank(hai.getAssignee())) {
			String userName = findStartEventAssignee(hai.getProcessInstanceId());
			historyVO.setAssignee(userName);
		} else if (hai.getActType().equals("endEvent")) {
			historyVO.setColour(consentColor);
		}
		String taskId = hai.getTaskId();
		TbCompleteTaskStatusEntity statusServiceOne = completeTaskStatusService.getOne(new LambdaQueryWrapper<TbCompleteTaskStatusEntity>()
			.eq(TbCompleteTaskStatusEntity::getTaskId, taskId));
		if (ObjectUtil.isNotEmpty(statusServiceOne)) {
			if (consent.equals(statusServiceOne.getStatus())) {
				//蓝色
				historyVO.setColour(consentColor);
			} else if (notConsent.equals(statusServiceOne.getStatus())) {
				//红色
				historyVO.setColour(notConsentColor);
			} else if (reload.contains(statusServiceOne.getStatus())) {
				//蓝色
				historyVO.setColour(consentColor);
			}
			historyVO.setApprovalProposal(statusServiceOne.getApprovalProposal());
		} else {
			//如果为空证明还在审批中 蓝色
			historyVO.setColour(consentColor);
		}
	}

	/**
	 * 查询任务发起人
	 *
	 * @param processInstanceId
	 */
	private String findStartEventAssignee(String processInstanceId) {
		TbBusinessEntity business = businessService.getOne(new LambdaQueryWrapper<TbBusinessEntity>()
			.eq(TbBusinessEntity::getProcinstId, processInstanceId));
		String createUserid = business.getCreateUserid();
		return findUserRealName(createUserid);
	}


	/**
	 * 查询候选人
	 *
	 * @param processInstanceId
	 * @return
	 */
	private String findCandidate(String processInstanceId) {
		TaskService taskService = Activiti7Util.taskService;
		Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
		List<IdentityLink> identityLinksForTask = taskService.getIdentityLinksForTask(task.getId());
		StringBuilder candidates = new StringBuilder();
		for (IdentityLink identityLink : identityLinksForTask) {
			if (StringUtil.isNotBlank(identityLink.getUserId())) {
				candidates.append(findUserRealName(identityLink.getUserId())).append(",");
			} else if (StringUtil.isNotBlank(identityLink.getGroupId())) {
				candidates.append(findGroupName(identityLink.getGroupId())).append(",");
			}
		}
		return candidates.substring(0, candidates.length() - 1);
	}

	/**
	 * 查询用户组名称
	 *
	 * @param groupId
	 * @return
	 */
	private String findGroupName(String groupId) {
		RoleEntity roleOne = roleService.getOne(new LambdaQueryWrapper<RoleEntity>()
			.eq(RoleEntity::getRoleId, groupId));
		return roleOne.getRoleName();
	}

	/**
	 * 查询用户名称
	 *
	 * @param userId
	 */
	private String findUserRealName(String userId) {
		UserEntity user = userService.getOne(new LambdaQueryWrapper<UserEntity>()
			.eq(UserEntity::getUserId, userId));
		return user.getUserRealName();
	}
}




